<?php

namespace App\Http\Controllers;

use App\Exports\ArchiveVolume10Export;
use App\Exports\ArchiveVolumeExport;
use App\Exports\AccountArchiveExport;
use App\Exports\FullIndexExport;
use App\Exports\SearchStage\UpBookCatalogExport29;
use App\Exports\SearchStage\UpBookCatalogExport8;
use App\Exports\SearchStage\UpFullIndexExport;
use App\Imports\ArchiveManageVolumeImport;
use App\Imports\AccountArchiveImport;
use App\Models\ArchiveManageVolume;
use App\Models\AccountArchive;
use App\Models\FullIndex;
use App\Models\Menu;
use App\Models\PartCompany;
use App\Models\PartCompanyClassify;
use App\Models\Project;
use App\Models\ProjectClassify;
use App\Services\ApprovalService;
use App\Services\ArchiveManageService;
use App\Services\AttachmentService;
use App\Services\CommonService;
use App\Services\DownloadJobService;
use App\Services\ProjectClassifyService;
use App\Services\ProjectService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Maatwebsite\Excel\Facades\Excel;

class FullIndexController extends Controller
{
    public $accountArchiveService;

    public function __construct(ArchiveManageService $accountArchiveService)
    {
        parent::__construct();
        $this->accountArchiveService = $accountArchiveService;
    }

    /**
     * 获取业务规范类列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-29 9:09
     */
    public function getList(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id'); //参建单位id
        $ptType    = $request->input('pt_type');
        $keyword   = $request->input('keyword');
        $perPage   = $request->input('per_page') ?: $this->limit;
        $ids       = [];
        $tables    = [];
        $partCompanyIds = ApprovalService::getPartCompanyIds($projectId, $ptType);
        foreach ($partCompanyIds as $partCompanyId) {
            $projectClassifyIds = ProjectClassifyService::getProjectClassifyIds($partCompanyId);
            foreach ($projectClassifyIds as $projectClassifyId) {
                $table = "book_titles_{$partCompanyId}_{$projectClassifyId}";
                if (Schema::hasTable($table)) {
                    $tables[] = "book_titles_{$partCompanyId}_{$projectClassifyId}";
                    $ids[] = $projectClassifyId;
                }
            }
        }
        $list = ProjectClassify::query()
            ->whereIn('id', array_unique($ids))
            ->where('part_company_id', '>', 0)
            ->when($keyword, function ($query) use ($keyword) {
                return $query->where('title', 'like', "%{$keyword}%");
            })
            ->select('id', 'title', 'archives_no', 'part_company_id', 'part_company_type', 'parent_id', 'classify_id')
            ->orderBy('part_company_type')
            ->orderBy('part_company_id')
            ->paginate($perPage)
            ->toArray();

        $project = Project::query()->find($projectId);
        foreach ($list['data'] as &$val) {
            $val['part_company_type_text'] = PartCompany::TYPE[$val['part_company_type']];
            $val['data_count'] = 0;
            $val['part_company_name'] = PartCompany::query()->where('id', $val['part_company_id'])->value('title');
            $fullIndex = FullIndex::query()->where('part_company_id', $val['part_company_id'])->where('project_classify_id', $val['id'])->first();
            $val['download_url'] = $fullIndex ? $fullIndex->download_url : '';
            $val['create_count'] = $fullIndex ? $fullIndex->create_count : 0;
            $val['updated_at']   = $fullIndex ? date('m月d H点i', strtotime($fullIndex->updated_at)) : '-';
            $val['status']       = $fullIndex ? $fullIndex->status : 0;
            if (str_contains($val['archives_no'], '[项目代码]')) {
                $val['archives_no'] = str_replace('[项目代码]', $project->document_number, $val['archives_no']);
            }
            foreach ($tables as $table) {
                $tableParam = CommonService::getTableParams($table);
                if ($tableParam['id2'] == $val['id']) {
                    $val['data_count'] += DB::table($table)->whereNull('deleted_at')->count(); //这里要用累加，因为同一个单位工程可能有多个参建单位做
                }
            }
            $val['is_click'] = 0;
        }
        $status = FullIndex::query()->where('project_id', $projectId)->pluck('status');
        $status = $status->isNotEmpty() ? $status->toArray() : [];
        $list['sendApiRequest'] = in_array(2, $status) ? 1 : 0; //如果有2，说明有正在合成的，需要继续请求

        return $this->success($list);
    }

    /**
     * 修改状态 ，2代表进行生成download_url中
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2025-01-11 15:52
     */
    public function updateStatus(Request $request) : JsonResponse
    {
        $projectId         = $request->input('project_id');
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $fullIndex         = FullIndex::query()->where('part_company_id', $partCompanyId)->where('project_classify_id', $projectClassifyId)->first();
        if (empty($fullIndex)) { //如果没有，就创建一条数据
            $fullIndex = new FullIndex();
            $fullIndex->project_id          = $projectId;
            $fullIndex->part_company_id     = $partCompanyId;
            $fullIndex->project_classify_id = $projectClassifyId;
        }
        $fullIndex->status = 2;
        $fullIndex->save();

        return $this->success('', '操作成功！');
    }

    /**
     * 导出数据
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @author: lxk
     * @date: 2025-01-11 14:28
     */
    public function createUrl(Request $request): JsonResponse
    {
        $projectId         = $request->input('project_id');
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleInstance = CommonService::getBookTitleInstance($partCompanyId, $projectClassifyId);
        $bookTitleIds      = $bookTitleInstance->pluck('id')->toArray();
        $eachChunk         = 20;
        $arrChunks         = array_chunk($bookTitleIds, $eachChunk); //选中的book_title_ids分割，每部分几个元素
        $dirName           = '卷内目录_' . ProjectClassify::query()->where('id', $projectClassifyId)->value('title') . '_' . date('H点i分s秒');
        $combinationId     = Project::query()->where('id', $projectId)->value('combination_id');
        foreach ($arrChunks as $ids) {
            $serialNos = DownloadJobService::getChildSerialNos($bookTitleInstance, $ids);
            $filePath  = 'public/excels/' . $dirName .'/'. $serialNos. '_卷内目录_' . date('His') . '.xlsx';
            switch ($combinationId) {
                case 1: //29号文格式
                    (new UpFullIndexExport($projectClassifyId, $partCompanyId, $ids, $serialNos))->store($filePath);
                    break;
                default://8号文
                    (new UpFullIndexExport($projectClassifyId, $partCompanyId, $ids, $serialNos))->store($filePath);
                    break;
            }
        }
        $downloadUrl = (new DownloadJobService())->mergeExcel("storage/excels/$dirName");
        $fullIndex = FullIndex::query()->where('part_company_id', $partCompanyId)->where('project_classify_id', $projectClassifyId)->first();
        $fullIndex->status = 1;
        $fullIndex->download_url = $downloadUrl;
        $fullIndex->create_count = $fullIndex->create_count + 1;
        $fullIndex->save();

        return $this->success('', '已生成');
    }

}
